<?php

namespace SunAdmin\Middleware;

use app\Request;
use think\facade\Config;
use think\Response;

class AllowCrossDomain
{
    /**
     * 允许跨域的域名
     */
    protected $cookieDomain;

    public $allowHeaders = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => 86400,
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',

    ];

    /**
     * @param Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        $this->cookieDomain = Config::get('cookie.domain', '');
        $header = $this->allowHeaders;
        $origin = $request->header('origin');
        if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))){
            $header['Access-Control-Allow-Origin'] = $origin;
        }
        if ($request->method(true) == 'OPTIONS') {
            $response = Response::create('ok')->code(200)->header($header);
        } else {
            $response = $next($request)->header($header);
        }
        $request->filter(['strip_tags', 'addslashes', 'trim']);
        return $response;
    }
}